package uzpay

import (
	"context"

	xerrors "gitee.com/liuxuezhan/ar-platform/admin-api/pkg/xerrors/assets"
	"gitee.com/liuxuezhan/ar-platform/pay-channel-packet/uzpay/uzpay/tool"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/bytedance/sonic"
	"github.com/zeromicro/go-zero/core/logc"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UzpayPayoutNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// uzpay代付回调通知
func NewUzpayPayoutNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UzpayPayoutNotifyLogic {
	return &UzpayPayoutNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UzpayPayoutNotifyLogic) UzpayPayoutNotify(req *types.UzPayoutNotifyReq) (resp *types.UzPayoutNotifyResp, err error) {
	b, _ := sonic.Marshal(req)

	params := make(map[string]any)
	params["tradeResult"] = req.TradeResult
	params["merTransferId"] = req.MerTransferId
	params["merNo"] = req.MerNo
	params["tradeNo"] = req.TradeNo
	params["transferAmount"] = req.TransferAmount
	params["applyDate"] = req.ApplyDate
	params["version"] = req.Version
	params["respCode"] = req.RespCode
	// 获取 uzpay 配置信息
	order, err := l.svcCtx.AssetsRpc.PayWithdraw.WithdrawListPage(l.ctx, &rpc.FindWithDrawReq{OrderNo: req.MerTransferId})
	if err != nil {
		return nil, err
	}
	sign, err := tool.GenerateSignature(params, order.Data[0].Channel[order.Data[0].WithdrawChannelId].SecretKey)
	if sign != req.Sign {
		logc.Error(l.ctx, "signature verification failed: ", sign, req.Sign)
		return nil, xerrors.ErrSignVerifyFailed
	}
	// 根据订单状态处理业务逻辑
	if req.TradeResult == "1" {
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawSuccess(l.ctx, &rpc.SuccessWithDrawReq{OrderNo: req.MerTransferId, Data: string(b)})
	} else {
		_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawFail(l.ctx, &rpc.FailWithDrawReq{OrderNo: req.MerTransferId, Data: string(b)})
	}
	if err != nil {
		logc.Error(l.ctx, err, string(b))
	}
	return
}
